<template>
	<div class="role-manage">
		<div class="query-form">
			<el-form ref="form" :inline="true" :model="queryForm">
				<el-form-item label="角色名称" prop="roleName">
					<el-input v-model="queryForm.roleName" placeholder="请输入角色名称" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="getRoleList">查询</el-button>
					<el-button @click="handleReset(form)">重置</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="base-table">
			<div class="action">
				<el-button type="primary" @click="handleAdd">创建</el-button>
			</div>
			<el-table :data="roleList">
				<el-table-column
					v-for="item in columns"
					:key="item.prop"
					:prop="item.prop"
					:label="item.label"
					:width="item.width"
					:formatter="item.formatter"
				>
				</el-table-column>
				<el-table-column label="操作" width="260">
					<template #default="scope">
						<el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
						<el-button size="small" type="primary" @click="handleOpenPermission(scope.row)">设置权限</el-button>
						<el-button type="danger" size="small" @click="handleDel(scope.row._id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				class="pagination"
				background
				layout="prev, pager, next"
				:total="pager.total"
				:page-size="pager.pageSize"
				@current-change="handleCurrentChange"
			/>
		</div>
		<el-dialog :title="actionName + '用户'" v-model="showModal" :before-close="dialogClose">
			<el-form ref="dialogForm" :model="roleForm" label-width="100px" :rules="rules">
				<el-form-item label="角色名称" prop="roleName">
					<el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input type="textarea" :rows="2" v-model="roleForm.remark" placeholder="请输入备注" />
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleClose(dialogForm)">取 消</el-button>
					<el-button type="primary" @click="handleSubmit(dialogForm)">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 权限弹框-->
		<el-dialog title="权限设置" v-model="showPermission">
			<el-form label-width="100px">
				<el-form-item label="角色名称">
					{{ curRoleName }}
				</el-form-item>
				<el-form-item label="选择权限">
					<el-tree
						ref="tree"
						:data="menuList"
						show-checkbox
						node-key="_id"
						default-expand-all
						:props="{ label: 'menuName' }"
					>
					</el-tree>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="showPermission = false">取 消</el-button>
					<el-button type="primary" @click="handlePermissionSubmit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script setup>
import { nextTick, onMounted, reactive, ref, toRaw } from "vue";
import api from "@/api";
import util from "@/utils/util";
import { ElMessage } from "element-plus";
// 表单引用
const form = ref();
const dialogForm = ref();
const queryForm = reactive({
	roleName: "",
});
const tree = ref();
// 定义表格需要的类名
const columns = reactive([
	{
		label: "角色名称",
		prop: "roleName",
	},
	{
		label: "备注",
		prop: "remark",
	},
	{
		label: "权限列表",
		prop: "permissionList",
		width: 200,
		formatter: (row, column, value) => {
			let names = [];
			let list = value.halfCheckedKeys || [];
			list.map((key) => {
				let name = actionMap[key];
				if (key && name) names.push(name);
			});
			return names.join(",");
		},
	},
	{
		label: "创建时间",
		prop: "createTime",
		// 转北京时间
		formatter(row, column, value) {
			return util.utc2beijing(value);
		},
	},
]);
// 角色列表
const roleList = ref([]);
// 分页
const pager = reactive({
	total: 0,
	pageNum: 1,
	pageSize: 10,
});
// dialog是否展开
const showModal = ref(false);
// 操作对应的单词
const action = ref("create");
// 操作对应的名称
const actionName = ref("创建");
let roleForm = ref({
	remark: "",
	roleName: "",
});
const rules = {
	roleName: [
		{
			required: true,
			message: "请输入角色角色名称",
		},
	],
};
// 权限展示
const showPermission = ref(false);
const curRoleId = ref("");
const curRoleName = ref("");
const menuList = ref([]);
// 菜单映射表
const actionMap = ref({});
onMounted(() => {
	// 获取用户列表
	getRoleList();
	// 获取菜单列表
	getMenuList();
});
// 角色列表初始化
function getRoleList() {
	try {
		const params = {
			...queryForm,
			...pager,
		};
		api.getRoleList(params).then((result) => {
			console.log(result);
			let { list, page } = result;
			roleList.value = list;
			pager.total = page.total;
		});
	} catch (e) {
		console.log(e);
		throw new Error(e);
	}
}

// 点击右上角的×, 关闭对话框
function dialogClose() {
	handleClose(dialogForm.value);
}
// 菜单列表初始化
function getMenuList() {
	try {
		let list = api.menuList();
		menuList.value = list;
		getActionMap(list);
	} catch (e) {
		console.log(e);
		throw new Error(e);
	}
}
// 表单重置
function handleReset(formEl) {
	formEl.resetFields();
}
// 角色添加
function handleAdd() {
	action.value = "create";
	actionName.value = "创建";
	showModal.value = true;
}
// 角色编辑
function handleEdit(row) {
	console.log(row);
	action.value = "edit";
	actionName.value = "编辑";
	showModal.value = true;
	nextTick(() => {
		roleForm.value = {
			_id: row._id,
			roleName: row.roleName,
			remark: row.remark,
		};
	});
}
// 角色删除
function handleDel(_id) {
	action.value = "delete";
	actionName.value = "删除";
	api.roleOperate({ _id, action: "delete" }).then((res) => {
		if (res) {
			ElMessage.success(actionName.value + "成功");
			getRoleList();
		}
	});
}
// 弹框关闭
function handleClose(dialogForm) {
	handleReset(dialogForm);
	showModal.value = false;
}
// 角色提交
function handleSubmit(formRef) {
	formRef.validate(async (valid) => {
		if (valid) {
			// let { roleForm, action } = this;
			// console.log(this);
			// let params = { ...roleForm, action };
			let params = { ...toRaw(roleForm.value) };
			params.action = action.value;
			api.roleOperate(params).then((res) => {
				if (res) {
					showModal.value = false;
					ElMessage.success(actionName.value + "成功!");
					handleReset(formRef);
					getRoleList();
				} else {
					ElMessage.error(actionName.value + "失败!");
				}
			});
		}
	});
}
function handleCurrentChange(current) {
	pager.pageNum = current;
	getRoleList();
}
function handleOpenPermission(row) {
	curRoleId.value = row._id;
	curRoleName.value = row.roleName;
	showPermission.value = true;
	let { checkedKeys } = row.permissionList;
	console.log(checkedKeys);
	setTimeout(() => {
		tree.checkedKeys = checkedKeys;
	});
}
function handlePermissionSubmit() {
	let nodes = tree.getCheckedNodes();
	let halfKeys = tree.getHalfCheckedKeys();
	let checkedKeys = [];
	let parentKeys = [];
	nodes.map((node) => {
		if (!node.children) {
			checkedKeys.push(node._id);
		} else {
			parentKeys.push(node._id);
		}
	});
	let params = {
		_id: curRoleId,
		permissionList: {
			checkedKeys,
			halfCheckedKeys: parentKeys.concat(halfKeys),
		},
	};
	api.updatePermission(params);
	showPermission.value = false;
	ElMessage.success("设置成功");
	getRoleList();
}
function getActionMap(list) {
	let actionMapObj = {};
	const deep = (arr) => {
		while (arr.length) {
			let item = arr.pop();
			if (item.children && item.action) {
				actionMapObj[item._id] = item.menuName;
			}
			if (item.children && !item.action) {
				deep(item.children);
			}
		}
	};
	deep(JSON.parse(JSON.stringify(list)));
	actionMap.value = actionMapObj;
}
</script>
<style lang="scss"></style>
